/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.service.menu.impl;

import com.je.common.base.DynaBean;
import com.je.common.base.constants.tree.NodeType;
import com.je.common.base.exception.PlatformException;
import com.je.common.base.exception.PlatformExceptionEnum;
import com.je.common.base.mapper.query.NativeQuery;
import com.je.common.base.service.CommonService;
import com.je.common.base.service.MetaResourceService;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.rpc.BeanService;
import com.je.common.base.service.rpc.SystemSettingRpcService;
import com.je.common.base.util.StringUtil;
import com.je.core.entity.extjs.JSONTreeNode;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.rbac.rpc.PermissionRpcService;
import com.je.rbac.service.menu.AppMenusService;
import com.je.rbac.service.permission.template.PcMenuDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class AppMenusServiceImpl implements AppMenusService {
    /**
     * 改模块对应的表
     */
    private static final String TABLECODE = "JE_META_APPS_MENU";
    @Autowired
    private MetaService metaService;
    @Autowired
    private MetaResourceService metaResourceService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private BeanService beanService;
    @Autowired
    private PermissionRpcService permissionRpcService;
    @Autowired
    private PcMenuDataService pcMenuDataService;

    @Override
    public JSONTreeNode loadAppMenus(String departmentId,String accountId, String tenantId, String appId) {
        List<DynaBean> metaApps = metaResourceService.selectByNativeQuery(NativeQuery.build().tableCode("JE_META_APPS").eq("APPS_APPID", appId).eq("APPS_QY", "1"));
        if (metaApps == null || metaApps.size() == 0) {
            return null;
        }
        if (metaApps.size() > 1) {
            throw new PlatformException("appId重复！", PlatformExceptionEnum.UNKOWN_ERROR);
        }

        List<String> menuPermissionList = permissionRpcService.findAccountMenuPermissions(departmentId,accountId, tenantId);
        NativeQuery menuWrapper = NativeQuery.build();
        menuWrapper.tableCode(TABLECODE);
        menuWrapper.eq("MENU_QY", "1").eq("JE_META_APPS_ID", metaApps.get(0).getStr("JE_META_APPS_ID"));

        menuWrapper.orderByAsc("SY_TREEORDERINDEX");
        List<DynaBean> menuBeanList = metaResourceService.selectByNativeQuery(menuWrapper);

        List<JSONTreeNode> nodeList = new ArrayList<>();
        JSONTreeNode template = beanService.getTreeTemplate(TABLECODE);

        //遍历结果构建树形节点对象
        menuBeanList.forEach(record -> {
            if (record.get("JE_CORE_MENU_ID") == null) {
                System.out.println(record.get("MENU_MC"));
                return;
            }
            if (!menuPermissionList.contains(pcMenuDataService.formatMenuDataShowTemplate(record.get("JE_CORE_MENU_ID").toString()))) {
                return;
            }
            //主键
            String nodeId = (String) record.get(template.getId());
            JSONTreeNode node = new JSONTreeNode();
            node.setId(nodeId);
            node.setText((String) record.get(template.getText()));
            //编码
            node.setCode((String) record.get(template.getCode()));
            //父节点
            node.setParent((String) record.get(template.getParent()));
            //节点信息
            if (StringUtil.isNotEmpty(template.getNodeInfo())) {
                node.setNodeInfo(StringUtil.getClobValue(record.get(template.getNodeInfo())));
            }
            //节点信息类型
            if (StringUtil.isNotEmpty(template.getNodeInfoType())) {
                node.setNodeInfoType(record.get(template.getNodeInfoType()) + "");
            }
            //是否叶子
            if (StringUtil.isNotEmpty(template.getNodeType())) {
                node.setLeaf(NodeType.LEAF.equalsIgnoreCase(record.get(template.getNodeType()) + ""));
                node.setNodeType(record.get(template.getNodeType()) + "");
            }
            if (StringUtil.isNotEmpty(template.getLayer())) {
                node.setLayer(record.get(template.getLayer()) + "");
            }
            //图标图片地址
            if (StringUtil.isNotEmpty(template.getIcon())) {
                node.setIcon(record.get(template.getIcon()) + "");
            }
            //图标样式
            if (StringUtil.isNotEmpty(template.getIconColor())) {
                node.setIconColor(record.get(template.getIconColor()) + "");
            }
            //是否禁用
            if (StringUtil.isNotEmpty(template.getDisabled())) {
                node.setDisabled(record.get(template.getDisabled()) + "");
            } else {
                node.setDisabled("0");
            }
            //树形路径
            if (StringUtil.isNotEmpty(template.getNodePath())) {
                node.setNodePath(record.get(template.getNodePath()) + "");
            }
            //描述
            if (StringUtil.isNotEmpty(template.getDescription())) {
                node.setDescription(StringUtil.getClobValue(record.get(template.getDescription())));
            }
            //排序
            if (StringUtil.isNotEmpty(template.getOrderIndex())) {
                node.setOrderIndex(record.get(template.getOrderIndex()) + "");
            }
            if (StringUtil.isNotEmpty(template.getTreeOrderIndex())) {
                node.setTreeOrderIndex(record.get(template.getTreeOrderIndex()) + "");
            }
            node.setBean(record.getValues());
            nodeList.add(node);
        });

        JSONTreeNode rootNode = commonService.buildJSONNewTree(nodeList, "ROOT");

        return rootNode;
    }

    @Override
    public List<Map<String, Object>> loadAppQuickMenus(String accountId, String tenantId, String appId) {
        ConditionsWrapper wrapper = ConditionsWrapper.builder();
        wrapper.table("JE_CORE_KJMENU");
        wrapper.eq("KJMENU_YHUD", accountId);
        wrapper.eq("KJMENU_TYPE", "app");
        wrapper.eq("KJMENU_APPID", appId);

        List<Map<String, Object>> quickBeanList = metaService.selectSql(wrapper);
//        List<String> menuPermissionList = permissionRpcService.findAccountMenuPermissions(accountId, tenantId);
//        List<Map<String, Object>> permdList = new ArrayList<>();
//        for (Map<String, Object> eachMap : quickBeanList) {
//            if (!menuPermissionList.contains(pcMenuDataService.formatMenuDataShowTemplate(eachMap.get("KJMENU_CDID").toString()))) {
//                continue;
//            }
//            permdList.add(eachMap);
//        }
        return quickBeanList;
    }

    @Override
    public List<Map<String, Object>> loadAppHistoryMenus(String accountId, String tenantId, String appId) {

        ConditionsWrapper wrapper = ConditionsWrapper.builder();
        wrapper.table("JE_RBAC_MENUHISTORY");
        wrapper.eq("MENUHISTORY_USER_ID", accountId);
        wrapper.eq("MENUHISTORY_APPID", appId);

        wrapper.orderByDesc("MENUHISTORY_CZSJ");
        List<Map<String, Object>> resultList = metaService.selectSql(wrapper);
//        List<String> menuPermissionList = permissionRpcService.findAccountMenuPermissions(accountId, tenantId);
//        List<Map<String, Object>> permdList = new ArrayList<>();
//        for (Map<String, Object> eachMap : resultList) {
//            if (!menuPermissionList.contains(pcMenuDataService.formatMenuDataShowTemplate(eachMap.get("JE_CORE_MENU_ID").toString()))) {
//                continue;
//            }
//            permdList.add(eachMap);
//        }
        return resultList;
    }
}
